<?php

/**
 * 公众号通用 以后的只要配置/config/weChatOptions.php和global.php的里域名
 * Created by PhpStorm.
 * User: wyr
 * Date: 14-10-8
 * Time: 下午9:17
 */
class Controller_Wwwmall2_Abstract extends FController
{

    public $openid;

    public $user;

    public $send_low_money;

    public $config;

    public function beforeAction()
    {
        global $_F;
//$this->openDebug();
        /*if ($this->is_weixin() === false) {
            die('请在微信客户端打开链接');
        }*/
        //$_F['uid'] = 1;

        /*$info = FCookie::get('_base');
        $controller = strtolower($_F['controller']);
        if(empty($info) && $controller == 'controller_wwwmall2_index'){
            FResponse::redirect('/location/index');
        }else{
            $_F['info'] = json_decode($this->js_unescape($info),true);
        }*/

        $_F['s_url'] = 'http://img1.yuanfenba.net';
        $_F['s_url_oss'] = 'http://image1.yuanfenba.net'; //FConfig::get('global.s_url_oss');
//var_dump($_F['info']);exit;
//        return true;

        $common_peizhi = Service_Order::Peizhi();
        $this->send_low_money = $common_peizhi['price_send'];
        $this->assign('send_low_money',$this->send_low_money);

        $this->checkAuth();
        //$this->openid = 'oQBIz1GyziL_rLQl8QPuCYP3Z2Xc';
        //$this->user = Service_User::getUserInfo($this->openid);


        if(empty($this->user)) $this->error('用户不存在');

        $_F['uid'] = $this->user['uid'];

        $this->assign('user',$this->user);

        $this->config = Service_Order::Peizhi();
        $this->assign('config',$this->config);
        return true;
    }

    private function checkAuth(){
        $cookie_appid = FCookie::get('appid');
        $appid = FConfig::get('wechat.appid');
        if($cookie_appid == $appid && FCookie::get('openid')){
            $this->openid = FCookie::get('openid');
            $this->user = Service_User::getUserInfo($this->openid);
        }else{
            require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
            $options = array(
                'token' => FConfig::get('wechat.token'),
                'appid' => FConfig::get('wechat.appid'),
                'appsecret' => FConfig::get('wechat.appsecret'),
            );
            $weixin = new WeixinChat($options);
            if(FRequest::getString('code') != ''){
                $code = FRequest::getString('code');
                $result = $weixin->getSnsAccessToken($code);
                $this->openid = $result['openid'];
                if(empty($this->openid)){
                    header("Content-type: text/html; charset=utf-8");
                    die('获取用户基本信息失败!');
                }
                $user_token = $result['access_token'];//用户令牌

                $result = $weixin->getSnsUserInfo($user_token,$this->openid);
                $user = Service_User::getUserInfo($this->openid);

                $user = Service_User::saveUser($result,$user);
                $this->user = $user;
                FCookie::set('appid',$options['appid'],30*86400);
                FCookie::set('openid',$this->openid,30*86400);
            }else{
                $weixin->redirectGetOauthCode($this->getFullUrl(),1);
            }
        }
    }

    /**
     * @return string
     */
    function getFullUrl(){
        global $_F;
        $url = 'http://' . $_F['http_host'] . $_F['uri'];
        if($_F['query_string'] != ''){
            $url .= '?' . $_F['query_string'];
        }
        return $url;
    }

    function showMessage($message, $msgType, $url = null)
    {
        echo "<script>alert('{$message}');";
        if ($url) echo "location='{$url}';";
        echo "</script>";
    }

    /**
     * 判断是否为微信，是微信就用微信登录，不是就是wap
     * @return bool
     */
    protected function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    /**
     * 是否已关注
     * @return bool true 为已关注
     */
    protected function isSubscribe()
    {
        global $_F;
        $openid = $_F['openid'];
        if ($this->is_weixin()) {
            if ($openid) {
                return Service_User::isSubscribe($openid);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /**不否为苹果系统
     * @return bool true是，false否
     */
    protected function is_ios()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
            return true;
        } else {
            return false;
        }
    }

    private function js_unescape($str)
    {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            if ($str[$i] == '%' && $str[$i+1] == 'u') {
                $val = hexdec(substr($str, $i+2, 4));
                if ($val < 0x7f) $ret .= chr($val);
                else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
                else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
                $i += 5;
            } else if ($str[$i] == '%') {
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            } else $ret .= $str[$i];
        }
        return $ret;
    }

    /**
     * 购物车优惠提示
     * @param int $cart_list_price
     * @return string
     */
    public function cart_tips($cart_list_price = 0){
        global $_F;
        $firstOrder = Service_Order::firstOrder($_F['uid']);
        if($firstOrder){
            $first_reduce_money = $this->formatPrice($this->config['first_reduce_money']);
            return "首单立减<b>{$first_reduce_money}</b>元";
        }else{
            $full_discount = json_decode($this->config['full_discount'],true);
            foreach ($full_discount as $k=>$v){
                if($k == 0 && $v['pay_money'] > $cart_list_price){
                    $pay_money = $this->formatPrice($v['pay_money']);
                    $reduce_money = $this->formatPrice($v['reduce_money']);
                    return "满<b>{$pay_money}</b>减<b>{$reduce_money}</b>元";
                }
                if($v['pay_money'] < $cart_list_price && (!empty($full_discount[$k+1]) && $full_discount[$k+1]['pay_money'] > $cart_list_price)){
                    $pay_money = $this->formatPrice($full_discount[$k+1]['pay_money']);
                    $reduce_money = $this->formatPrice($full_discount[$k+1]['reduce_money']);
                    return "满<b>{$pay_money}</b>减<b>{$reduce_money}</b>元";
                }elseif(empty($full_discount[$k+1])){
                    $pay_money = $this->formatPrice($v['pay_money']);
                    $reduce_money = $this->formatPrice($v['reduce_money']);
                    return "满<b>{$pay_money}</b>减<b>{$reduce_money}</b>元";
                }
            }
        }
    }

    /**
     * 获取订单满减金额
     * @param int $cart_list_price
     * @return float
     */
    public function fullReduce($cart_list_price){
        $full_discount = json_decode($this->config['full_discount'],true);
        foreach ($full_discount as $k=>$v){
            if($k == 0 && $v['pay_money'] > $cart_list_price){
                return 0;
            }
            if($v['pay_money'] < $cart_list_price && (!empty($full_discount[$k+1]) && $full_discount[$k+1]['pay_money'] > $cart_list_price)){
                return $v['reduce_money'];
            }elseif(empty($full_discount[$k+1])){
                return $v['reduce_money'];
            }
        }
    }

    /**
     * 格式化价格
     * @param $price
     * @return string
     */
    public function formatPrice($price){
        if(strpos('.',$price) !== false){
            $price = trim($price,'0');
            $price = trim($price,'0');
            $price = trim($price,'.');
        }
        return $price;
    }
}
